import paramiko
import threading
import time

# 配置信息
USERNAME = 'wheeltec'
PASSWORD = 'dongguan'
LEADER_SCRIPT = '~/wheeltec_ros2/src/wheeltec_multi/scripts/leadercar.sh'
SLAVE_SCRIPT = '~/wheeltec_ros2/src/wheeltec_multi/scripts/slavecar_12.sh'

# IP地址列表 - 第一个是leader，其余是slave
IP_LIST = [
    # 在这里添加你的IP地址，第一个是leader
     '192.168.0.100',
     '192.168.0.101',
     '192.168.0.102',
     '192.168.0.103',
     '192.168.0.104',
     '192.168.0.105',
     '192.168.0.106',
     '192.168.0.107',
    # ...
]

def execute_ssh_command(ip, script, is_leader=False):
    try:
        # 创建SSH客户端
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        
        # 连接到服务器
        client.connect(ip, username=USERNAME, password=PASSWORD, timeout=10)
        
        # 执行命令
        if is_leader:
            print(f"在Leader {ip} 上执行 {LEADER_SCRIPT}")
            command = f"bash {LEADER_SCRIPT}"
        else:
            print(f"在Slave {ip} 上执行 {SLAVE_SCRIPT}")
            command = f"bash {SLAVE_SCRIPT}"
        
        # 打开交互式shell
        shell = client.invoke_shell()
        shell.send(command + '\n')
        
        # 保持连接
        print(f"{ip} 上的命令已发送，保持连接...")
        while True:
            time.sleep(1)
            
    except Exception as e:
        print(f"在 {ip} 上执行命令时出错: {str(e)}")
    finally:
        # 不要关闭连接，保持脚本运行
        pass

def main():
    if not IP_LIST:
        print("错误: IP列表为空，请编辑脚本添加IP地址")
        return
    
    threads = []
    
    # 启动leader
    leader_ip = IP_LIST[0]
    t = threading.Thread(target=execute_ssh_command, args=(leader_ip, LEADER_SCRIPT, True))
    t.start()
    threads.append(t)
    
    # 启动slaves
    for slave_ip in IP_LIST[1:]:
        t = threading.Thread(target=execute_ssh_command, args=(slave_ip, SLAVE_SCRIPT, False))
        t.start()
        threads.append(t)
    
    # 等待所有线程
    for t in threads:
        t.join()

if __name__ == '__main__':
    main()
